/*
 * Copyright (C) 2022 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xjh.him.fragment.profile;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.xjh.him.R;
import com.xjh.him.core.BaseFragment;
import com.xjh.him.databinding.FragmentProfileBinding;
import com.xjh.him.dto.user.UserDTO;
import com.xjh.him.fragment.other.AboutFragment;
import com.xjh.him.fragment.other.SettingsFragment;
import com.xjh.him.utils.Utils;
import com.xjh.him.utils.XToastUtils;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.textview.supertextview.SuperTextView;
import com.xuexiang.xutil.file.FileUtils;
import com.xuexiang.xutil.net.JsonUtil;
import com.ypx.imagepicker.bean.ImageItem;
import com.ypx.imagepicker.data.OnImagePickCompleteListener;

import org.xjh.tool.Checks;

import java.util.ArrayList;

/**
 * @author xuexiang
 * @since 2019-10-30 00:18
 */
@Page(anim = CoreAnim.none)
public class ProfileFragment extends BaseFragment<FragmentProfileBinding>
        implements SuperTextView.OnSuperTextViewClickListener {
    /**
     * 传递的参数名
     */
    public static final String KEY_USER_DTO_NAME = "userDTO";

    private UserDTO userDTO;


    public ProfileFragment(UserDTO userDTO) {
        this.userDTO = userDTO;
    }

    @NonNull
    @Override
    protected FragmentProfileBinding viewBindingInflate(LayoutInflater inflater, ViewGroup container) {
        return FragmentProfileBinding.inflate(inflater, container, false);
    }

    /**
     * @return 返回为 null意为不需要导航栏
     */
    @Override
    protected TitleBar initTitle() {
        return null;
    }

    /**
     * 初始化控件
     */
    @Override
    protected void initViews() {
        hideCurrentPageSoftInput();
        loadViews(this.userDTO);
    }

    public void loadViews(UserDTO userDTO) {
        if (userDTO != null) {
            Glide.with(this).load(userDTO.getAvatarUrl()).into(binding.rivAvatar);
            binding.tvNickname.setText(userDTO.getNickname());
        }
    }


    @Override
    protected void initListeners() {
        binding.menuAvatar.setOnSuperTextViewClickListener(this);
        binding.menuNickname.setOnSuperTextViewClickListener(this);
        binding.menuSignature.setOnSuperTextViewClickListener(this);
        binding.menuSettings.setOnSuperTextViewClickListener(this);
        binding.menuAbout.setOnSuperTextViewClickListener(this);
    }


    @SingleClick
    @Override
    public void onClick(SuperTextView view) {
        int id = view.getId();
        if (id == R.id.menu_settings) {
            openNewPage(SettingsFragment.class);
        } else if (id == R.id.menu_about) {
            openNewPage(AboutFragment.class);
        } else if (id == R.id.menu_avatar) {
            updateAvatar();
        } else if (id == R.id.menu_nickname) {
            openNewPage(UpdateNicknameFragment.class, KEY_USER_DTO_NAME, userDTO);
        }else if (id == R.id.menu_signature) {
            openNewPage(UpdateSignatureFragment.class, KEY_USER_DTO_NAME, userDTO);
        }
    }

    /**
     * 更换头像
     */
    private void updateAvatar() {
        Utils.getWeChatPickerBuilder()
            .setMaxCount(1)
            .pick(requireActivity(), new OnImagePickCompleteListener() {
                @Override
                public void onImagePickComplete(ArrayList<ImageItem> items) {
                    if (!Checks.isEmpty(items)) {
                        ImageItem imageItem = items.get(0);

                        //上传图片
                        String uploadUrl = Utils.getSevServerApiUrl(getContext(),
                                getString(R.string.api_img_upload));
                        SimpleCallBack<String> uploadCB = new SimpleCallBack<String>() {
                            @Override
                            public void onSuccess(String imgUrl) throws Throwable {
                                if (!Checks.isEmpty(imgUrl)) {
                                    //更新用户信息
                                    String updateInfoUrl = Utils.getWebServerApiUrl(getContext(),
                                            getString(R.string.api_user_update_info));
                                    UserDTO params = new UserDTO();
                                    params.setId(userDTO.getId());
                                    params.setAvatarUrl(imgUrl);
                                    SimpleCallBack<Boolean> updateCB = new SimpleCallBack<Boolean>() {
                                        @Override
                                        public void onSuccess(Boolean success) throws Throwable {
                                            if (!success) {
                                                XToastUtils.toast("更新用户信息失败");
                                            }
                                        }

                                        @Override
                                        public void onError(ApiException e) {

                                        }
                                    };
                                    Utils.doPost(updateInfoUrl, JsonUtil.toJson(params), updateCB);
                                    //加载图片
                                    userDTO.setAvatarUrl(imgUrl);
                                    Glide.with(getContext()).load(userDTO.getAvatarUrl()).into(binding.rivAvatar);
                                }
                            }

                            @Override
                            public void onError(ApiException e) {

                            }
                        };
                        Utils.uploadFile(uploadUrl, FileUtils.getFileByPath(imageItem.getPath()), uploadCB);
                    }
                }
            });
    }
}
